/**
 * 
 */
package com.beta.common.web;

import com.baomidou.mybatisplus.plugins.Page;
import com.beta.common.model.ErrorResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @author vector
 *
 */
public abstract class AbstractBaseController {

	@Autowired
	protected HttpServletRequest request;
	
	@Autowired
	protected HttpServletResponse response;

	public String getMessage(String code) {
		return new RequestContext(request).getMessage(code);
	}

	public <T> ResponseEntity<T> ok() {
		return ResponseEntity.ok().body(null);
	}
	
	public <T> ResponseEntity<T> ok(T data) {
		return ResponseEntity.ok().body(data);
	}

	public <T> ResponseEntity<T> ok(int httpStatus, T data) {
		return ResponseEntity.status(httpStatus).body(data);
	}

	public ResponseEntity<?> error(String code) {
		return error(HttpStatus.SC_UNPROCESSABLE_ENTITY, code);
	}

	public ResponseEntity<?> error(int httpStatus, String code) {
		return error(httpStatus, code, getMessage(code));
	}

	public ResponseEntity<?> error(int httpStatus, String code, String message) {
		return ResponseEntity.status(httpStatus).body(new ErrorResponse(code, message));
	}

	public ResponseEntity<?> pageData(Page<?> pageData) {
		Map<String, Object> result = new HashMap<>();
		result.put("total", pageData.getTotal());
		result.put("rows", pageData.getRecords());
		result.put("current", pageData.getCurrent());
		result.put("size", pageData.getSize());
		return ResponseEntity.ok(result);
	}

	public <T, R> ResponseEntity<?> pageData(Page<T> pageData, Function<T, R> rowMapper) {
		Map<String, Object> result = new HashMap<>();
		result.put("total", pageData.getTotal());
		result.put("current", pageData.getCurrent());
		result.put("size", pageData.getSize());

		List<T> records = pageData.getRecords();
		List<R> mappedRows = new ArrayList<R>();
		if (CollectionUtils.isNotEmpty(records)) {
			records.forEach(row -> {
				mappedRows.add(rowMapper.apply(row));
			});
		}
		result.put("rows", mappedRows);
		return ResponseEntity.ok(result);
	}

	public <T> Page<T> getMybatisPage() {
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		if (StringUtils.isEmpty(page)) {
			page = "1";
		}
		if (StringUtils.isEmpty(pageSize)) {
			pageSize = "20";
		}
		return new Page<T>(Integer.parseInt(page), Integer.parseInt(pageSize));
	}

	protected String getClientIp() {
		return IPUtil.getIPAddress(request);
	}

}
